package com.zhoug.common3demo;

import android.os.Bundle;
import android.util.Base64;

import com.zhoug.common3.content.SharedPreferencesWrap;
import com.zhoug.common3.interfaces.IEncryptor;
import com.zhoug.encrypt3.AESHelper;
import com.zhoug.encrypt3.EncryptConstants;
import com.zhoug.logger3.Logger;

import java.nio.charset.StandardCharsets;


public class MainActivity extends MyBaseActivity {
    private static final String TAG = ">>>MainActivity";
    /**
     * 默认AES/CBC加密的key
     */
    private static String defaultKey = "hasdkf1sdkh3288jk1234jhj321nhjaa";
    /**
     * 默认iv向量
     */
    private static String defaultIv = "ryCTej14GO1oly2A";
    private com.zhoug.encrypt3.IEncryptor encryptor;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main;
    }

    @Override
    protected void findViews() {

    }

    @Override
    protected void onCreate1(Bundle savedInstanceState) {
        SharedPreferencesWrap sp = SharedPreferencesWrap.with(this);
        sp.setEncryptEnable(true);
        sp.setEncryptor(new IEncryptor() {
            @Override
            public String decryptToString(String s) {
                return getEncryptor().decryptToString(s);
            }

            @Override
            public String encryptToBase64(String s) {
                return getEncryptor().encryptToBase64(s);
            }
        });
        sp.edit().putString("name","张三").apply();
        String name = sp.getString("name", null);
        Logger.d(TAG, "name:"+name);

    }


    /**
     * 加密器
     *
     * @return
     */
    private com.zhoug.encrypt3.IEncryptor getEncryptor() {
        if (encryptor == null) {
            synchronized (this) {
                if (encryptor == null) {
                    //默认加密器
                    encryptor = new AESHelper.Builder()
                            .setCharset(StandardCharsets.UTF_8)
                            .setBase64Flag(Base64.NO_WRAP | Base64.NO_PADDING)
                            .setTransformation(EncryptConstants.TRANSFORMATION_AES_CBC_P7)
                            .setKey(defaultKey)
                            .setIv(defaultIv)
                            .build();
                }
            }
        }
        return encryptor;
    }
}